class MyPageHeader extends BaseEditMaster {
    constructor(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
            returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl) {
        super(dataId, currentTaskPrivileges, nextTaskPrivileges, pageStatus, pageListData,
                returnUrl, fetchDataUrl, saveUrl, exportUrl, printUrl);
        this.hasFilterValue = true; // 目的为了使用自定义参数取得数据，负责会用基类参数
    }
    // 得到数据
    GetEntityData() {
        let item = {};
        item['wareHouseId'] = parseInt($("#WareHouseId").val());
        item['wareHouseNo'] = $.trim($("#WareHouseNo").val());                                // 材料组编号
        item['wareHouseName'] = $.trim($("#WareHouseName").val());                            // 材料组名称
        item['wareHouseAdress'] = $.trim($("#WareHouseAdress").val());
        item['description'] = formatNullInputValue($.trim($("#Description").val()));  // 备注
        item['createdBy'] = $.trim($("#UserId").val());
        item['updatedBy'] = $.trim($("#UserId").val());

        return JSON.stringify(item);
    }
    GetFilterValue() {
        let params = {};
        params['WareHouseId'] = parseInt(this.dataId);
        params['Limit'] = parseInt($("#page-size").val());
        params['PageIndex'] = 1;

        return params;
    }
    FillData(data) {
        let item = data.HeaderEntity;
        $("#WareHouseId").val(item.wareHouseId);
        $("#WareHouseNo").val(item.wareHouseNo);
        $("#WareHouseName").val(item.wareHouseName);
        $("#WareHouseAdress").val(item.wareHouseAdress);
        $("#Description").val(item.description);

        $("#WareHouseNo").focus();

        // 显示明细数据
        _InstancePageLines.BuildDataTable(data.LocationList);
    }
    Save() {
        super.Save(function (data, $self) {
            if (data > 0) {
                if (parseInt($self.pageStatus) === 1) {
                    $("#WareHouseId").val(data);   // 设置刚才插入的记录ID
                    $self.dataId = data;
                    $("#panelSlave").show();
                }
            }
        });
    }
    New() {
        super.New();
        // 默认设置一些值
        $("#WareHouseId").val(0);
        $('#tabData01 tbody').empty();
        $("#panelSlave").hide();
        _InstancePageLines.rows = 0;
        $("#WareHouseNo").focus();
    }
    Expand() {
        super.Expand(function () { });
    }
    /* 折叠 */
    Collapse() {
        super.Collapse(function () { });
    }
}

class MyPageLines extends BaseEditSlave {
    constructor() {
        super('', '', '');
    }
    GetFilterValue(pageIndex) {
        if (pageIndex !== 0) {
            $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", pageIndex);
        }

        let params = {};
        params['WareHouseId'] = parseInt($("#WareHouseId").val());
        params['Limit'] = parseInt($("#page-size").val());
        params['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page"));

        return JSON.stringify(params);
    }
    FetchLinesByHeaderKey(pageIndex) {
        $.ajax({
            type: "POST",
            url: parent.basePath + "/master/warehouse_location/fetchForPage.html",
            timeout: 30 * 1000,
            data: this.GetFilterValue(pageIndex),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
            }
        }).done((data) => {
            if (data.Success)
                this.BuildDataTable(data);
            else {
                $('#tabData01 tbody').empty();
                ShowErrorMessagePanel("没有找到符合条件的数据。");
            }
        }).fail((data) => {
            ajaxError(data, 1);
        }).always(() => {
        });
    }
    BuildDataTable(result) {
        $("#panelSlave").show();
        if (result.Success === false) {
            $('#tabData01 tbody').empty();
            $('#loading').hide();
            return false;
        }
        // 设置翻页控件
        if (result.TotalPages > 0) {  //总页数
            $("#wrapper__navbar").data("swPagination").options.max_page = result.TotalPages;
        } else {
            $("#wrapper__navbar").data("swPagination").options.max_page = 1;
        }
        if (result.PageIndex > 0) { //当前页数
            $("#wrapper__navbar").data("swPagination").options.current_page = result.PageIndex;
            $("#wrapper__navbar").data("swPagination").setPage(result.PageIndex);
        } else {
            $("#wrapper__navbar").data("swPagination").options.current_page = 1; //当前页数
            $("#wrapper__navbar").data("swPagination").setPage(1);
        }
        // 得到数据列表
        result = result.DataList;
        $('#tabData01 tbody').empty();
        // 得到数据列表
        if (result === null || result.length === 0) {
            this.rows = 0;
            return false;
        }
        let content_01 = '';
        this.rows = result.length;
        this.numCheckbox = result.length;
        for (let i = 0; i < result.length; i++) {
            let id = result[i].locationId;
            content_01 += '<tr _mash_id="' + id + '">';
            content_01 += '<td style="padding-left:6px; vertical-align:middle;"><label class="btn" for="R-' + id + '"><input id="R-' + id + '" name="_check_row" type="checkbox" onclick="_InstancePageLines.DoCheckRow($(this),\'_check_row\', $(\'#CheckAll\'));" value="' + id + '"/><i></i><span></span></label></td>';
            content_01 += '<td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.DeleteLines($(this));"><i class="fa-all fa-trash-o fa-1"></i></span></td>';
            content_01 += '<td style="border-right:none;">' + formatNullData(result[i].locationNo) + '</td>';
            content_01 += '</tr>';

            $('#tabData01 tbody').append(content_01);
            content_01 = '';
        }
        setOneTableRowColor("tabData01");
        $(window).resize();               // 防止因为出现滚动条而造成画面显示问题
        $('#loading').hide();
    }
    DeleteLines($self) {
        let params = {};
        params['LocationId'] = $self.parent().parent().attr("_mash_id");
        params['LocationNo'] = $self.parent().parent().find("td").eq(2).text();
        params['WareHouseId'] = parseInt($("#WareHouseId").val());
        params['DeletedBy'] = $.trim($("#UserId").val());
        params['Limit'] = parseInt($("#page-size").val());
        params['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page"));

        super.DeleteLines(params, "/master/warehouse_location/delete.html", function (data, $self) {
            $self.BuildDataTable(data);
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    //新增
    NewLines() {
        var $newLine = $('<tr class="newLine" _mash_id="0">' +
                '    <td ></td>' +
                '    <td class="column__action"><span title="删除" class="trash" onclick="_InstancePageLines.RemoveNewLine($(this))"><i class="fa-all fa-trash-o fa-1"></i></span></td>' +
                '    <td class="edited-cell" style="border-right:none;"></td>' +
                '</tr>');
        $('#tabData01 tbody').prepend($newLine);   // 加在前面
        this.rows = this.rows + 1;

        setOneTableRowColor("tabData01");

        let id = "cellField";
        let name = "_cellField";
        $newLine.find("td.edited-cell").click(function () {
            OnCellClickEvent($(this), id, name, 0);
        });
    }
    //保存
    SaveLines() {
        let _result = {};
        let _itemList = [];
        $('#tabData01 tbody').find("tr").each(function () {
            if ($(this).find("td.dirty").length) {
                let item = {};
                item['wareHouseId'] = parseInt($("#WareHouseId").val());
                item['locationNo'] = $(this).find("td").eq(2).text();
                item['createdBy'] = parseInt($.trim($("#UserId").val()));
                item['updatedBy'] = parseInt($.trim($("#UserId").val()));
                _itemList.push(item);
            }
        });
        _result['InsertList'] = _itemList;
        _result['WareHouseId'] = parseInt($("#WareHouseId").val());
        _result['Limit'] = parseInt($("#page-size").val());
        _result['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page"));

        // 保存，增加明细记录
        super.DoAjax(_result, "/master/warehouse_location/insert.html", (data, $self) => {
            $self.BuildDataTable(data);
            ShowSuccessMessagePanel('增加成功。');
        });
    }
    RemoveNewLine($self) {
        parent.showModal(350, 140, '删除确认', '', null, null, 1, '请问，确定要删除当前行吗？', function () {
            $self.parent().parent().remove();
            this.rows = this.rows - 1;
            this.numCheckbox = this.numCheckbox - 1;
        });
    }
    GetCheckedLinesData() {
        let _result = {};
        let itemList = [];
        $('#tabData01 tbody').find("tr").each(function () {
            if ($(this).children("td").eq(0).children("label").eq(0).children("input[type='checkbox'][name='_check_row']").is(":checked") === true) {
                var instance = {};
                instance['locationId'] = $(this).attr("_mash_id");
                instance['locationNo'] = $.trim($(this).find("td").eq(2).text());
                instance['updatedBy'] = $.trim($("#UserId").val());
                instance['deletedBy'] = $.trim($("#UserId").val());
                itemList.push(instance);
            }
        });
        _result['DeleteList'] = itemList;
        _result['WareHouseId'] = parseInt($("#WareHouseId").val());
        _result['Limit'] = parseInt($("#page-size").val());
        _result['PageIndex'] = parseInt($("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page"));
        return JSON.stringify(_result);
    }
    BatchDeleteLines() {
        if ($('#tabData01 tbody').find("tr.row__selected").length === 0) {
            ShowErrorMessagePanel("请先选择要删除的数据。");
            return false;
        }
        super.BatchDeleteLines("/master/warehouse_location/batch_delete.html", function (data, $self) {
            $self.BuildDataTable(data);
            $("#CheckAll").prop("checked", false);
            ShowSuccessMessagePanel('删除成功。');
        });
    }
    // 设置行选择后的状态
    SetRowStatus($self) {
        super.AdjustRowStatus($self, ($row, index) => {
            let key = $self.val();
            let item = {};
            // 设置 编辑、删除按钮失效
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", "");
        }, ($row, index) => {
            let key = $self.val();
            // 设置 编辑、删除按钮有效
            let _event_delete_onclick = '_InstancePageLines.DeleteLines($(this))';
            $row.children('td').eq(1).children('span').eq(0).attr("onclick", _event_delete_onclick);
        });
    }
}

let _InstancePageHeader = null;
let _InstancePageLines = null;

//-----------------------------------------------------------------------------
// 页面初始化
//-----------------------------------------------------------------------------
function onPageReady() {
    let _pageStatus = parseInt($("#Action").val());
    let _dataId = $("#WareHouseId").val();

    let warehouse_list_result = $.cookie("warehouse_list_result") === undefined ? "" : $.cookie("warehouse_list_result");
    let _pageListData = [];
    if (warehouse_list_result !== "") {
        _pageListData = warehouse_list_result.split(',');
        $("#rec_total_rows").text(_pageListData.length);
        $("#rec_cur_row").text($.inArray(_dataId, _pageListData) + 1);

        if (_pageListData.length > 0) {
            let index = $.inArray(_dataId, _pageListData);
            if (index === 0) {
                $("#ButPrev").attr("disabled", "disabled");
            } else {
                $("#ButNext").removeAttr("disabled");
            }
            if (index === (_pageListData.length - 1)) {
                $("#ButNext").attr("disabled", "disabled");
            } else {
                $("#ButPrev").removeAttr("disabled");
            }
        }
    } else {
        $("#rec_total_rows").text("1");
        $("#rec_cur_row").text("1");
    }

    _InstancePageHeader = new MyPageHeader(_dataId, 0, 0, _pageStatus, _pageListData,
            "/master/warehouse/list.html",
            "/master/warehouse/fetchByKey.html",
            "/master/warehouse/save.html",
            "/master/warehouse/export.html",
            "/master/warehouse/print.html");

    _InstancePageLines = new MyPageLines();

    $("#tabPanelHeader").wxTabs({tabContent: "tabPanelContent"});

    // 设置分页控制 （操作区域）
    $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", 1);
    $("#wrapper__navbar").swPagination({
        link_string: '/?page={page_number}',
        max_page: null,
        paged: function (page) {
            $("abbr.page_indicator_block,#wrapper__navbar").attr("_msh_page", page);
            _InstancePageLines.FetchLinesByHeaderKey(page);
        }
    });

    $("#hPanelSplitter").click(function () {
        if ($(this).children("i").hasClass("fa-angle-double-up")) {
            _InstancePageHeader.Collapse();
        } else {
            _InstancePageHeader.Expand();
        }
    });

    _InstancePageHeader.OnPageLoad();
}

// 画面大小或者位置移动
function onPageResize() {
}

//-----------------------------------------------------------------------------
// 验证函数
//-----------------------------------------------------------------------------
$.validator.setDefaults({
    ignore: 'hidden, [reaonly=readonly]'
});
$(function () {
    $("#form_data").validate({
        // Step 1：设置验证规则和错误消息
        rules: {
            _WareHouseNo: "required",
            _WareHouseAdress: "required",
            _WareHouseName: "required"
        },
        messages: {
            _WareHouseNo: "请填写仓库编号。",
            _WareHouseAdress: "请填写仓库地址。",
            _WareHouseName: "请填写仓库名称。"

        },
        // Step 2：设置验证触发事件
        onclick: false,
        onfocusout: false,
        onfocusin: false,
        onkeyup: false,
        onkeydown: false,
        focusInvalid: false,
        // Step 3：设置错误信息提示
        showErrors: window.showErrors  //使用自定义的错误显示方法
    });
});